import React, { createContext, useContext, useEffect, useState } from "react";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { createStackNavigator } from "@react-navigation/stack";
import { useNavigation } from "@react-navigation/native";

import { FontAwesome, Ionicons, Entypo, AntDesign } from "@expo/vector-icons";
import UserContext from "./src/sdk/context/userContext";
import CoupleUserContext from "./src/sdk/context/coupleContext";
import PreferenceContext from "./src/sdk/context/preferenceContext";
import MetricsContext from "./src/sdk/context/metricsContext";
import UserBlogContext from "./src/sdk/context/blogContext";
import ShipContext from "./src/sdk/context/shipContext";
import Match from "./src/component/Match/Match";
import MYInfo from "./src/component/MYInfo/MYInfo";
import ProfileEdit from "./src/component/MYInfo/ProfileEdit/ProfileEdit";
import AccountAndSecurity from "./src/component/MYInfo/AccountAndSecurity/AccountAndSecurity";
import { NavigationContainer } from "@react-navigation/native";
import LoginByCode from "./src/component/Login/LoginByCode";
import Login from "./src/component/Login/Login";
import RegisterByCode from "./src/component/Register/RegisterByCode";
import Register from "./src/component/Register/Register";
import TAInfo from "./src/component/TAInfo/TAInfo";
import Feedback from "./src/component/TAInfo/Feedback/Feedback";
import PersonalityTest from "./src/component/MYInfo/ProfileEdit/PersonalityTest/PersonalityTest";
import PreferenceBasic from "./src/component/Match/UserPreference/PreferenceTest/PreferenceBasic";
import PreferenceComplex from "./src/component/Match/UserPreference/PreferenceTest/PreferenceComplex";
import ChatScreen from "./src/component/TAInfo/Chat/Chat";
import RegisterProfile from "./src/component/Register/RegisterProfile";
import axios from "axios";
import Const from "./src/sdk/const";
import setAuthToken from "./src/sdk/utils/authToken";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Alert } from "react-native";

const Tab = createBottomTabNavigator();
const Stack = createStackNavigator();

function tabBarIcon(name) {
  return ({ color, size }) => (
    <FontAwesome name={name} color={color} size={size} />
  );
}

function BottomTabs() {
  const { user, setUser } = useContext(UserContext);
  const { coupleUser, setCoupleUser } = useContext(CoupleUserContext);
  const { meShip, taShip, setMeShip, setTaShip } = useContext(ShipContext);
  // const [hasMatch, setHasMatch] = useState(false);
  const size = 24;
  const color = "gray";

  useEffect(() => {
    console.log("首次进入---开始查找是否有匹配用户...", user);
    axios
      .get(`${Const.baseURL}/user/determineToMatchPages/${user["userId"]}`)
      .then((res) => {
        console.log("开始获取TA的信息", res.data);
        if (res.data.data) {
          // setHasMatch(true);
          setCoupleUser({ ...res.data.data });
          console.log(JSON.stringify(res.data.data));
          let taId = res.data.data["userId"];
          let meId = user["userId"];
          console.log("开始检查我的「确认关系」状态...");
          axios
            .get(`${Const.baseURL}/match/oppositePartyStatus/${taId}`)
            .then((res) => {
              console.log("我是否想确认关系：", res.data.data);
              if (res.data.data == true) {
                // setShip({ ...ship, "me": 1 });
                setMeShip(1);
              } else {
                setMeShip(0);
                // setShip({ ...ship, "me": 0 });
              }
              axios
                .get(`${Const.baseURL}/match/oppositePartyStatus/${meId}`)
                .then((res) => {
                  console.log("TA是否想确认关系：", res.data.data);
                  if (res.data.data == true) {
                    // setShip({ ...ship, "ta": 1 });
                    setTaShip(1);
                  } else {
                    // setShip({ ...ship, "ta": 0 });
                    setTaShip(0);
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          setCoupleUser({});
          // setHasMatch(false);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  useEffect(() => {
    if (taShip === 1 && meShip === 1) {
      console.log("双方想确认关系");
    } else if (taShip === 1 && meShip === 0) {
      console.log("他确认关系");
    } else if (taShip === 0 && meShip === 1) {
      console.log("你想确认关系");
    } else if (taShip === 0 && meShip === 0) {
      console.log("无关系");
    }
  }, [taShip, meShip]);

  return (
    <>
      {user["isLogged"] == 1 ? (
        <Tab.Navigator
          initialRouteName="匹配"
          tabBarOptions={{
            activeTintColor: "#1DA1F2",
          }}
          screenOptions={{
            unmountOnBlur: true
          }}
        >
          <Tab.Screen
            name="TA"
            component={TAInfo}
            options={{
              tabBarIcon: () => (
                // <Ionicons name="meh" size={size} color={color} />
                <AntDesign name="meh" size={size} color={color} />
              ),
            }}
          />
          <Tab.Screen
            name="匹配"
            component={coupleUser["userId"] ? ChatScreen : Match}
            options={{
              tabBarIcon: () => (
                <Entypo name="circle" size={size} color={color} />
              ),
              headerShown: coupleUser["userId"] ? false : true,
            }}
          />

          <Tab.Screen
            name="我"
            component={MYInfo}
            options={{
              tabBarIcon: () => (
                <Ionicons name="person" size={size} color={color} />
              ),
            }}
          />
        </Tab.Navigator>
      ) : (
        <Stack.Navigator
          initialRouteName={Login}
          // initialRouteName={user["isLogged"] == 1 ? BottomTabs : Login}
          screenOptions={{ headerShown: false }}
        >
          <Stack.Screen name="Login" component={Login} />

          <Stack.Screen name="Register" component={Register} />
          <Stack.Screen name="LoginByCode" component={LoginByCode} />
          <Stack.Screen name="RegisterByCode" component={RegisterByCode} />
          <Stack.Screen name="RegisterProfile" component={RegisterProfile} />
        </Stack.Navigator>
      )}
    </>
  );
}

function MainPage() {
  const { user, setUser } = useContext(UserContext);
  const { coupleUser, setCoupleUser } = useContext(CoupleUserContext);
  const [systemWs, setSystemWs] = useState(null);
  const navigation = useNavigation();

  useEffect(() => {
    AsyncStorage.getItem("crucio-user")
      .then((res) => {
        if (res) {
          console.log(
            "🚀 ~ file: App.jsx:60 ~ AsyncStorage.getItem ~ res:",
            res
          );
          setUser(() => {
            return JSON.parse(res);
          });
          console.log(JSON.parse(res).token);
          AsyncStorage.getItem("crucio-user-token").then((res) => {
            if (res) {
              console.log("当前token", res);
              setAuthToken(res);
            }
          }).catch((err)=>{
            console.log("获取token失败")
            console.error(err)
          });
          console.log(JSON.parse(res).isAuthed, JSON.parse(res).isLogged);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  }, []);

  useEffect(() => {
    if (user["isLogged"] === 1) {
      if (user["isAuthed"] === 1) {
        navigation.navigate("BottomTabs");
      } else {
        navigation.navigate("RegisterProfile");
      }
    }
  }, [user["isAuthed"], user["isLogged"]]);

  useEffect(() => {
    if (user["userId"]) {
      console.log("开始监听系统通知");
      const socket = new WebSocket(
        `${Const.wsURL}/SystemEndPoint/${user["userId"]}`
      );
      setSystemWs(socket);
    } else {
      console.log("结束监听系统通知");
    }
  }, [user["userId"]]);

  useEffect(() => {
    if (systemWs) {
      // 设置WebSocket事件处理程序
      systemWs.onopen = () => {
        console.log("System WebSocket connected");
      };

      systemWs.onmessage = (event) => {
        const datastr = event.data;
        console.log(datastr);

        // 监听信息，再调查询匹配用户的接口
        if (datastr === "已经成功为您匹配到一位适配对象") {
          Alert.alert("已匹配到新用户", "", [
            {
              text: "确定",
              onPress: () => {
                axios
                  .get(
                    `${Const.baseURL}/user/determineToMatchPages/${user["userId"]}`
                  )
                  .then((res) => {
                    console.log("开始获取TA的信息", res.data);
                    if (res.data.data) {
                      // setHasMatch(true);
                      setCoupleUser({ ...res.data.data });
                      console.log(JSON.stringify(res.data.data));
                      let taId = res.data.data["userId"];
                      let meId = user["userId"];
                      console.log("开始检查我的「确认关系」状态...");
                      axios
                        .get(
                          `${Const.baseURL}/match/oppositePartyStatus/${taId}`
                        )
                        .then((res) => {
                          console.log("我是否想确认关系：", res.data.data);
                          if (res.data.data == true) {
                            // setShip({ ...ship, "me": 1 });
                            setMeShip(1);
                          } else {
                            setMeShip(0);
                            // setShip({ ...ship, "me": 0 });
                          }
                          axios
                            .get(
                              `${Const.baseURL}/match/oppositePartyStatus/${meId}`
                            )
                            .then((res) => {
                              console.log("TA是否想确认关系：", res.data.data);
                              if (res.data.data == true) {
                                // setShip({ ...ship, "ta": 1 });
                                setTaShip(1);
                              } else {
                                // setShip({ ...ship, "ta": 0 });
                                setTaShip(0);
                              }
                            })
                            .catch((err) => {
                              console.log(err);
                            });
                        })
                        .catch((err) => {
                          console.log(err);
                        });
                    } else {
                      setCoupleUser({});
                      // setHasMatch(false);
                    }
                  })
                  .catch((err) => {
                    console.log(err);
                  });
              },
            },
          ]);
        }else{
          const res = JSON.parse(datastr);
          if(res["theme"]==="cutLove"){
            Alert.alert(res["message"],"", [
              {
                text: "确定",
                onPress: () => {
                  setCoupleUser({});
                  console.log("确定");
                },
              },
            ]);
          }
        }

        // if (datastr !== "已经成功为您匹配到一位适配对象") {
        //   const res = JSON.parse(datastr);
        //   if (res.system) {
        //     // 处理系统消息
        //   } else {
        //     // 处理非系统消息
        //     if (res.user) {
        //       Alert.alert("已匹配到新用户", "", [
        //         {
        //           text: "确定",
        //           onPress: () => {
        //             const id = res.user.userId;
        //             console.log("hi", id);
        //             // 根据id获取用户信息
        //             try {
        //               axios
        //                 .get(`${Const.baseURL}/user/getUserById/${id}`)
        //                 .then((res) => {
        //                   // const {...data } = res.data.data;
        //                   if (res.data["code"] === 200) {
        //                     console.log("success get couple user");
        //                     setCoupleUser({ ...res.data.data });
        //                   }
        //                   if (res.data["code"] === 400) {
        //                     console.log("fail to get couple user");
        //                   }
        //                   if (res.data["code"] === 401) {
        //                     console.log("no access to get couple user");
        //                   }
        //                 })
        //                 .catch((e) => {
        //                   console.error(e);
        //                 });
        //             } catch (error) {
        //               console.error(error);
        //             }
        //           },
        //         },
        //       ]);
        //     }
        //   }
        // }
      };

      systemWs.onclose = () => {
        console.log("System WebSocket disconnected");
      };
      // 在组件卸载时关闭WebSocket连接
      // return () => {
      //   socket.close();
      // };
    }
  }, [systemWs]);

  return (
    <Stack.Navigator
      initialRouteName={BottomTabs}
      // initialRouteName={user["isLogged"] == 1 ? BottomTabs : Login}
      screenOptions={{ headerShown: false }}
    >
      {
        user["isLogged"] == 1 ? (
          <>
          
      <Stack.Screen name="BottomTabs" component={BottomTabs} />
      <Stack.Screen name="ProfileEdit" component={ProfileEdit} />
      <Stack.Screen name="AccountAndSecurity" component={AccountAndSecurity} />
      <Stack.Screen name="TAInfo" component={TAInfo} />
      <Stack.Screen
        name="Feedback"
        component={Feedback}
        initialParams={{ exId: null }}
      />
      <Stack.Screen name="ChatScreen" component={ChatScreen} />
      <Stack.Screen name="MYInfo" component={MYInfo} />
      <Stack.Screen name="Match" component={Match} />

      <Stack.Screen name="PersonalityTest" component={PersonalityTest} />

      {/* 用户偏好测试 */}
      <Stack.Screen name="PreferenceBasic" component={PreferenceBasic} />
      <Stack.Screen name="PreferenceComplex" component={PreferenceComplex} />

      {/* 用户注册问题 */}
      <Stack.Screen name="RegisterProfile" component={RegisterProfile} />
      </>
        ) : (<>
        <Stack.Screen name="Login" component={Login} />
      <Stack.Screen name="LoginByCode" component={LoginByCode} />
      <Stack.Screen name="Register" component={Register} />
      <Stack.Screen name="RegisterByCode" component={RegisterByCode} />
        </>)
      }

    </Stack.Navigator>
  );
}
export default function App() {
  // const baseURL = `http://localhost:8080/api/`
  const [user, setUser] = useState({});
  const [coupleUser, setCoupleUser] = useState({});
  const [meShip, setMeShip] = useState(0);
  const [taShip, setTaShip] = useState(0);
  // const [user, setUser] = useState({ userId: 1 });
  const [preference, setPreference] = useState({});
  const [metrics, setMetrics] = useState({});
  const [userBlog, setUserBlog] = useState({});

  useEffect(() => {
    if (user.userId) {
      try {
        axios
          .get(`${Const.baseURL}/user/getUserById/${user["userId"]}`)
          .then((res) => {
            setUser({ ...res.data.data });
          });
      } catch (error) {
        console.error(error);
      }
    }
  }, []);
  // useEffect(() => {
  //   if (user.userId) {
  //     axios
  //       .get(`${Const.baseURL}/user/blog/getBlogByUserID/${user["userId"]}`)
  //       .then((res) => {
  //         //跳转登录页面
  //         if (res.data.code === 401) {
  //           setUser({});
  //           navigation.navigate("Login");
  //           return
  //         }
  //         if (res.data.code === 200){
  //           console.log("🚀 ~ file: App.jsx:240 ~ .then ~ res:", JSON.stringify(res.data))
  //           setUserBlog(res.data.data)
  //         }
  //       });
  //   }
  // }, [user["userId"]]);

  // TODO: 要改初始值（空）

  return (
    <UserContext.Provider value={{ user, setUser }}>
      <UserBlogContext.Provider value={{ userBlog, setUserBlog }}>
        <ShipContext.Provider value={{ meShip, taShip, setMeShip, setTaShip }}>
          <CoupleUserContext.Provider value={{ coupleUser, setCoupleUser }}>
            <MetricsContext.Provider value={{ metrics, setMetrics }}>
              <PreferenceContext.Provider value={{ preference, setPreference }}>
                <NavigationContainer>
                  <MainPage />
                </NavigationContainer>
              </PreferenceContext.Provider>
            </MetricsContext.Provider>
          </CoupleUserContext.Provider>
        </ShipContext.Provider>
      </UserBlogContext.Provider>
    </UserContext.Provider>
  );
}
